package org.bigpigman.el.common;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Description
 * @Author 朱咸军
 * @Date 2019/12/20
 **/
public class PoiTool {

    private static final List<String> dateDesList = new ArrayList<String>() {
        {
            add("年");
            add("月");
            add("日");
        }
    };

    private static String DATE_FORMAT_DEFAULT = "yyyy-MM-dd";

    /**
     * 获取Excel表格中的值,并将最终结果转化成字符串格式
     * @param cell
     * @return
     */
    public static String getCellValue(Cell cell, CellType cellType) {
        if (cell == null || cellType == null) {
            return null;
        }
        String rs = null;
        switch (cellType) {
            case STRING:
                rs = cell.getStringCellValue();
                break;
            case BOOLEAN:
                rs = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                rs = getCellValue(cell, cell.getCachedFormulaResultType());
                break;
            case NUMERIC:
                /**
                 * 关于数字类型的判断比较麻烦,因为在poi中,时间类型也是算在NUMERIC类型中的
                 */
                String formatStr = cell.getCellStyle().getDataFormatString();
                AtomicReference<Boolean> isDate = new AtomicReference<>(false);
                if (!StringTool.isNullOrEmpty(formatStr)) {
                    dateDesList.forEach(x -> isDate.set(isDate.get() || formatStr.contains(x)));//判断formatStr中是否含有年月日
                }
                if (DateUtil.isCellDateFormatted(cell) || DateUtil.isCellInternalDateFormatted(cell)) {
                    rs = new SimpleDateFormat(DATE_FORMAT_DEFAULT).format(DateUtil.getJavaDate(cell.getNumericCellValue()));
                } else if (isDate.get()) {
                    rs = new SimpleDateFormat(DATE_FORMAT_DEFAULT).format(cell.getDateCellValue());
                } else {
                    rs = String.valueOf(cell.getNumericCellValue());
                }
                break;
        }
        return rs;
    }
}
